package com.citycloud.ccuap.tc.admin.interceptor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.citycloud.ccuap.commons.log.LogHelper;
import com.citycloud.ccuap.commons.model.ISysFunction;
import com.citycloud.ccuap.commons.web.session.CurrentUser;
import com.citycloud.ccuap.commons.web.session.SessionConstant;

@Component
public class OAuth2Interceptor implements HandlerInterceptor{
	@Value("${security.oauth2.client.user-logout}")
	private String logoutUrl;
	/** 日志处理 */
	protected static LogHelper logger = new LogHelper(OAuth2Interceptor.class);

	public static List<String> urls = new ArrayList<>();
	{
		urls.add("/admin/v1/yq/sysApp/uploadFile");
		urls.add("/admin/logingOut");
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

		logger.debug("afterCompletion...");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		logger.debug("postHandle...");
	}
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();
		if(uri.startsWith("//admin/")){
			return true;
		}
		for(String url : urls){
			if(url.endsWith(uri)){
				return true;
			}
		}
//		String uri = request.getRequestURI();
//		if(uri.startsWith("//ccuap/")){
//			return true;
//		}
//		for(String url : urls){
//			if(url.endsWith(uri)){
//				return true;
//			}
//		}
//		logger.debug("进入拦截器------");
//		HttpSession session = request.getSession();
//		CurrentUser currentUser = (CurrentUser) session.getAttribute(SessionConstant.CURRENT_USER_KEY);
//		logger.debug("进入拦截器------currentUser:{}"+currentUser+"{"+session+"}");
//		String requestAction = request.getServletPath();
//
//		logger.debug("你的当前请求地址：" + requestAction);
//		if (requestAction.equals("/error")) {
//			String jsonString = JSONUtil.getErrorJSONString("你的当前请求地址不存在！");
//			InterceptorHelper.wirteJsonToResponsee(jsonString, response);
//			return false;
//		}
//
//		if (currentUser == null) {
//			String errorMessage = "你还没有登录，请先登录！";
//			logger.info(errorMessage);
//			String url = Pac4jUtil.getRedirectionUrl(WebGlobalNames.LOGON_PAGE, request);
//			String jsonString = JSONUtil.getErrorJSONString(errorMessage, url);
//			InterceptorHelper.wirteJsonToResponsee(jsonString, response);
//			return false;
//		}
//
//		List<ISysFunction> functionList = currentUser.getFunctionList();
//		if (functionList == null || functionList.isEmpty()) {
//			String jsonString = JSONUtil.getErrorJSONString("你没有登录系统的权限！", WebGlobalNames.LOGON_PAGE);
//
//			InterceptorHelper.wirteJsonToResponsee(jsonString, response);
//			return false;
//		}
//
//		// LEAF等级不需要验证按钮权限
//		if (WebGlobalNames.RIGHT_VALIDATE_LEVER == GlobalFunctionType.LEAF || doValidateAccess(request, functionList)) {
//			logger.debug("你拥有访问权限:" + requestAction);
//
//			ISysFunction cuFunction = currentUser.getFunction();
//			if (cuFunction != null && cuFunction.getLogFlag() == 1) {
//				// 记录日志
//				String data = ResolveRequest.getParameters(request);
//				logger.info("========##=====提交数据(业务日志)1：" + data);
//
//				logger.doBizLog(currentUser, "业务日志", data, requestAction);
//			}
//
//			return true;
//		} else {
//			String errorMessage = "你没有访问权限:" + requestAction;
//			logger.info(errorMessage);
//			logger.doLog(currentUser, errorMessage, requestAction);
//
//			String jsonString = JSONUtil.getErrorJSONString(new Long(503), errorMessage);
//			InterceptorHelper.wirteJsonToResponsee(jsonString, response);
//			return false;
//		}
        return true;
	}

	/**
	 * 判断是否有访问权限
	 *
	 * @param req
	 * @param functionList
	 * @return boolean
	 */
	private boolean doValidateAccess(HttpServletRequest req, List<?> functionList) {
		String requestFunction = req.getServletPath();
		boolean hasAccess = false;

		for (Iterator<?> itFunc = functionList.iterator(); itFunc.hasNext();) {
			ISysFunction sysFunc = (ISysFunction) itFunc.next();
			String location = sysFunc.getLocation();
			if (location != null && location.indexOf("?") > 0) {
				location = location.substring(0, location.indexOf("?"));
			}

			if (requestFunction.equals(location)) {
				hasAccess = true;

				CurrentUser currentUser = (CurrentUser) req.getSession().getAttribute(SessionConstant.CURRENT_USER_KEY);
				currentUser.setFunction(sysFunc);
				break;
			}
		}

		return hasAccess;
	}

}
